package hzau.utils;

import java.util.Date;
import java.util.HashMap;

import hzau.constants.TokenConstant;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
public class JwtUtils {
/*
* 1.私有化构造方式,所以是工具类*/
    private JwtUtils(){}
    /*
    * 2.静态方法*/
    //生成token
    public static String genJwt(Long id){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("id",id);
        String jwt= Jwts.builder().setClaims(hashMap)
                .signWith(SignatureAlgorithm.HS256, TokenConstant.LOGIN_KEY)
                .setExpiration(new Date(System.currentTimeMillis()+3600*1000))
                .compact();
        return jwt;
    }
    //通过token获取id;
    //TODO bug 返回的的id只能先是Integer再是Long
    public  static Long getUserId(String jwt){
        Integer id=(Integer) Jwts.parser().setSigningKey(TokenConstant.LOGIN_KEY)
                .parseClaimsJws(jwt)
                .getBody().get("id");
        System.out.println(id);
        return Long.valueOf(String.valueOf(id));

    }
    //解析token
    public static  boolean testJwts(String jwt){

        try{ Jwts.parser().setSigningKey(TokenConstant.LOGIN_KEY)
                .parseClaimsJws(jwt)
                .getBody();
            return true;}
        catch (MalformedJwtException e ){
            return  false;
        }
        catch (SignatureException e){
            return  false;
        }
    }
    public static long parseToken(String token){
        try {
            long id = (long) Jwts.claims().get("id");
            return id;
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }
}
